<template>
  <el-container class="layout-container">
    <!-- 侧边栏 -->
    <el-aside :width="isCollapse ? '64px' : '200px'" class="sidebar-container">
      <div class="logo-container">
        <img src="@/assets/logo.png" alt="Logo" class="logo-img" v-if="!isCollapse">
        <h1 class="logo-title" v-if="!isCollapse">点餐管理系统</h1>
      </div>
      
      <el-menu
        :default-active="activeMenu"
        :collapse="isCollapse"
        :collapse-transition="false"
        background-color="#304156"
        text-color="#bfcbd9"
        active-text-color="#409eff"
        unique-opened
        router
      >
        <el-menu-item index="/">
          <el-icon><House /></el-icon>
          <template #title>首页</template>
        </el-menu-item>
        
        <!-- 动态菜单 -->
        <template v-for="menu in userMenus" :key="menu.id">
          <el-sub-menu v-if="menu.children && menu.children.length > 0" :index="menu.code">
            <template #title>
              <el-icon>
                <component :is="menu.icon" v-if="menu.icon" />
                <Setting v-else />
              </el-icon>
              <span>{{ menu.name }}</span>
            </template>
            <el-menu-item 
              v-for="child in menu.children" 
              :key="child.id" 
              :index="mapMenuPath(child.path)"
            >
              {{ child.name }}
            </el-menu-item>
          </el-sub-menu>
          
          <el-menu-item v-else :index="mapMenuPath(menu.path)">
            <el-icon>
              <component :is="menu.icon" v-if="menu.icon" />
              <Document v-else />
            </el-icon>
            <template #title>{{ menu.name }}</template>
          </el-menu-item>
        </template>
      </el-menu>
    </el-aside>
    
    <!-- 主体区域 -->
    <el-container>
      <!-- 头部 -->
      <el-header class="header-container">
        <div class="navbar-left">
          <el-icon class="menu-toggle" @click="toggleSidebar">
            <Expand v-if="isCollapse" />
            <Fold v-else />
          </el-icon>
        </div>
        
        <div class="navbar-right">
          <el-dropdown @command="handleCommand">
            <div class="user-info">
              <el-avatar :size="30" :src="userInfo.avatar || ''">
                {{ userInfo.username?.substring(0, 1) }}
              </el-avatar>
              <span class="username">{{ userInfo.username }}</span>
              <span class="user-role" v-if="userInfo.isAdmin">(管理员)</span>
            </div>
            
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                <el-dropdown-item command="settings">系统设置</el-dropdown-item>
                <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      
      <!-- 内容区域 -->
      <el-main class="main-container">
        <router-view />
      </el-main>
      
      <!-- 底部 -->
      <el-footer class="footer-container">
        餐饮点菜综合服务系统 ©2025
      </el-footer>
    </el-container>
  </el-container>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import {
  House,
  Setting,
  Dish,
  DataAnalysis,
  Expand,
  Fold,
  Document,
  Coffee,
  User
} from '@element-plus/icons-vue'

// 引入API
import { getUserInfo, logout, getUserMenus } from '@/api/auth'

const route = useRouter()
const router = useRouter()

// 状态管理
const isCollapse = ref(false)
const activeMenu = ref('/')
const userInfo = reactive({
  username: '管理员',
  avatar: '',
  isAdmin: false,
  roles: []
})

// 用户菜单
const userMenus = ref([])

// 菜单主题
const menuTheme = ref('default')

// 切换侧边栏
const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value
}

// 处理用户操作
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      // 跳转到个人中心
      router.push('/profile')
      break
    case 'settings':
      // 跳转到设置页面
      router.push('/settings')
      break
    case 'logout':
      // 退出登录
      handleLogout()
      break
  }
}

// 映射菜单路径到前端路由
const mapMenuPath = (path) => {
  if (!path) return '/'
  
  // 移除/api前缀并映射到前端路由
  if (path.startsWith('/api/')) {
    const newPath = path.substring(4) // 移除/api前缀
    // 特殊映射规则
    if (newPath === '/system') return '/roles'  // 系统管理默认跳转到角色管理
    if (newPath === '/system/role') return '/roles'
    if (newPath === '/system/permission') return '/permissions'
    if (newPath.startsWith('/dish')) return '/dishes'
    if (newPath.startsWith('/order')) return '/orders'
    if (newPath.startsWith('/table')) return '/tables'
    if (newPath.startsWith('/user')) return '/users'
    // 特殊处理管理员所有权限路径
    if (newPath === '/admin/**') return '/permissions'
    // 对于其他路径，移除/api前缀即可
    return newPath
  }
  
  // 如果是子菜单路径，也需要处理
  if (path.startsWith('/system/role')) return '/roles'
  if (path.startsWith('/system/permission')) return '/permissions'
  if (path.startsWith('/dish')) return '/dishes'
  if (path.startsWith('/order')) return '/orders'
  if (path.startsWith('/table')) return '/tables'
  if (path.startsWith('/user')) return '/users'
  
  // 特殊处理管理员所有权限路径
  if (path === '/api/admin/**') return '/permissions'
  
  return path
}

// 退出登录
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用登出接口
      await logout()
    } catch (err) {
      console.log('登出接口调用失败:', err)
    } finally {
      // 清除本地token
      localStorage.removeItem('admin-token')
      // 跳转到登录页
      router.push('/login')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const response = await getUserInfo()
    console.log('获取用户信息响应:', response)
    if (response.code === 200) {
      userInfo.username = response.data.username
      userInfo.avatar = response.data.avatar
      userInfo.isAdmin = response.data.isAdmin || false
      userInfo.roles = response.data.roles || []
    } else {
      ElMessage.error(response.message || '获取用户信息失败')
    }
  } catch (err) {
    console.log('获取用户信息失败:', err)
    ElMessage.error('获取用户信息失败')
  }
}

// 获取用户菜单
const fetchUserMenus = async () => {
  try {
    const response = await getUserMenus()
    console.log('获取用户菜单响应:', response)
    if (response.code === 200) {
      userMenus.value = response.data
      console.log('菜单数据:', response.data)
    } else {
      ElMessage.error(response.message || '获取用户菜单失败')
    }
  } catch (err) {
    console.log('获取用户菜单失败:', err)
    ElMessage.error('获取用户菜单失败: ' + (err.message || '未知错误'))
  }
}

// 处理菜单主题变化
const handleMenuThemeChange = (event) => {
  menuTheme.value = event.detail
  // 应用菜单主题
  applyMenuTheme(event.detail)
}

// 应用菜单主题
const applyMenuTheme = (theme) => {
  const sidebar = document.querySelector('.sidebar-container')
  if (!sidebar) return
  
  // 清除所有主题类
  sidebar.classList.remove('menu-theme-dark', 'menu-theme-light')
  
  // 应用新主题
  if (theme === 'dark') {
    sidebar.classList.add('menu-theme-dark')
  } else if (theme === 'light') {
    sidebar.classList.add('menu-theme-light')
  }
  // 默认主题不添加额外类
}

// 监听路由变化，更新激活菜单
activeMenu.value = route.path

// 页面加载时获取用户信息和菜单
onMounted(() => {
  fetchUserInfo()
  fetchUserMenus()
  
  // 监听菜单主题变化事件
  window.addEventListener('menu-theme-change', handleMenuThemeChange)
  
  // 应用保存的菜单主题
  const savedMenuTheme = localStorage.getItem('menuTheme') || 'default'
  applyMenuTheme(savedMenuTheme)
})

// 组件卸载前清理事件监听器
onBeforeUnmount(() => {
  window.removeEventListener('menu-theme-change', handleMenuThemeChange)
})
</script>

<style scoped>
.layout-container {
  height: 100vh;
}

.sidebar-container {
  background-color: #304156;
  transition: width 0.28s;
  overflow: hidden;
}

.logo-container {
  display: flex;
  align-items: center;
  height: 60px;
  padding: 0 15px;
  background-color: #2c3e50;
}

.logo-img {
  width: 32px;
  height: 32px;
  margin-right: 10px;
}

.logo-title {
  color: #fff;
  font-size: 16px;
  font-weight: 600;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.el-menu {
  border-right: none;
}

.header-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
  padding: 0 20px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.menu-toggle {
  font-size: 20px;
  cursor: pointer;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.username {
  margin-left: 10px;
  font-size: 14px;
  color: #666;
}

.user-role {
  margin-left: 5px;
  font-size: 12px;
  color: #999;
}

.main-container {
  background-color: #f0f2f5;
  padding: 20px;
}

.footer-container {
  height: 60px;
  line-height: 60px;
  text-align: center;
  color: #666;
  background-color: #f5f5f5;
  font-size: 14px;
}
</style>